using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Catastrophe.Common.FileM;
using Standard.Licensing;

namespace Catastrophe.Common.SoftLicensing
{
	/// <summary>
	/// 授权校验
	/// </summary>
	public class LicenseCheck
	{
		private LicenseManager _licManager;

		private License _license;

		private const int LicCheckInterval = 1;

		private string _localPwd;

		private Func<string, string> _funcPwd;

		public Action<LicCheckRet> LicTipHandler { get; set; }

		public LicenseCheck(string localPwd, Func<string, string> funcPwd)
		{
			this._localPwd = localPwd ?? throw new ArgumentNullException("localPwd");
			this._funcPwd = funcPwd ?? throw new ArgumentNullException("funcPwd");
		}

		public LicCheckRet SoftLicense()
		{
			LicCheckRet licCheckRet = new LicCheckRet();
			try
			{
				if (!File.Exists("license.lic"))
				{
					licCheckRet.Message = "缺少授权文件";
					return licCheckRet;
				}
				string pubKey = this.GetPubKey();
				if (string.IsNullOrWhiteSpace(pubKey))
				{
					licCheckRet.Message = "软件授权失败-缺少授权信息，请联系供应商!";
					return licCheckRet;
				}
				this._licManager = new LicenseManager();
				this._license = this._licManager.LoadLicense();
				Tuple<bool, string> tuple = this._licManager.ValidateLicense(this._license, pubKey);
				licCheckRet.Success = tuple.Item1;
				licCheckRet.Message = tuple.Item2;
				licCheckRet.PubKey = pubKey;
				if (this._license.Type == LicenseType.Trial)
				{
					Task.Run(delegate
					{
						this.SoftLicCheck(pubKey);
					});
				}
				return licCheckRet;
			}
			catch (Exception ex)
			{
				licCheckRet.Message = ex.Message;
				return licCheckRet;
			}
		}

		private void SoftLicCheck(string pubKey)
		{
			while (true)
			{
				Tuple<bool, string> tuple = this._licManager.ValidateLicense(this._license, pubKey);
				if (!tuple.Item1)
				{
					this.LicTipHandler?.Invoke(new LicCheckRet
					{
						Success = tuple.Item1,
						Message = tuple.Item2
					});
				}
				Thread.Sleep(60000);
			}
		}

		private string GetPubKey(string fileName = "license.lic")
		{
			//if (!File.Exists(fileName))
			//{
			//	throw new Exception("授权文件不存在!请联系供应商!");
			//}
			//XmlDocument xmlDocument =  new XmlDocument();
			//xmlDocument.Load(fileName);
			//xmlDocument.DocumentElement.SelectNodes();
			//         XmlNode xmlNode = xmlDocument.SelectXmlNode(xmlDocument, "License//LicenseAttributes");
			//string text = xmlNode.SelectSingleNode(".//Attribute[@name='SerialNo']")?.InnerText;
			//if (string.IsNullOrWhiteSpace(text))
			//{
			//	throw new Exception("授权失败!请生成序列号并联系供应商!");
			//}
			//if (this._localPwd != this._funcPwd(text))
			//{
			//	throw new Exception("授权失败!请生成序列号并联系供应商!");
			//}
			//XmlNode xmlNode2 = xmlNode.SelectSingleNode(".//Attribute[@name='PubKey']");
			//return xmlNode2.InnerText;
			return "";
		}
	}
}
